/**
 *    Copyright 2015 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.chenyuan.rediscache;

import com.chenyuan.entity.Blog;
import com.chenyuan.mapper.BlogMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mybatis.caches.redis.RedisCache;

import java.io.InputStream;

import static org.junit.Assert.*;

/**
 * Test with Ubuntu
 * sudo apt-get install redis-server
 * execute the test
 * 
 * @version $Id$
 */
public final class RedisTestCase {

  private static final String DEFAULT_ID = "REDIS";

  private static RedisCache cache;

  @BeforeClass
  public static void newCache() {
    cache = new RedisCache(DEFAULT_ID);
  }

  @Test
  public void shouldDemonstrateCopiesAreEqual() {
    for (int i = 0; i < 1000; i++) {
      cache.putObject(i, i);
      assertEquals(i, cache.getObject(i));
    }
  }

  @Test
  public void putBlog(){
    Blog blog1 = new Blog("chenyuan", "123", 1);
    Blog blog2 = new Blog("chenyuan2", "1234", 2);
    cache.putObject(1,blog1);
    cache.putObject(2,blog2);
  }

  @Test
  public void shouldRemoveItemOnDemand() {
    cache.putObject(0, 0);
    assertNotNull(cache.getObject(0));
    cache.removeObject(0);
    assertNull(cache.getObject(0));
  }

  @Test
  public void shouldFlushAllItemsOnDemand() {
    for (int i = 0; i < 5; i++) {
      cache.putObject(i, i);
    }
    assertNotNull(cache.getObject(0));
    assertNotNull(cache.getObject(4));
    cache.clear();
    assertNull(cache.getObject(0));
    assertNull(cache.getObject(4));
  }

  @Test(expected = IllegalArgumentException.class)
  public void shouldNotCreateCache() {
    cache = new RedisCache(null);
  }

  @Test
  public void shouldVerifyCacheId() {
    assertEquals("REDIS", cache.getId());
  }

  @Test
  public void shouldVerifyToString() {
    assertEquals("Redis {REDIS}", cache.toString());
  }

  /**
   * 一二级缓存共存时查询原理
   * <p>
   * 一二级缓存如果都开启的情况下，数据查询过程如下：
   * <p>
   * 当发起一个查询的时候，mybatis会先访问这个namespace对应的二级缓存，如果二级缓存中有数据则直接返回，否则继续向下；
   * <p>
   * 查询一级缓存中是否有对应的数据，如果有则直接返回，否则继续向下；
   * <p>
   * 访问db获取需要的数据，然后放在当前SqlSession对应的二级缓存中，并且在本地内存中的另外一个地方存储一份（这个地方我们就叫TransactionalCache）；
   * <p>
   * 当SqlSession关闭的时候，也就是调用SqlSession的close方法的时候，此时会将TransactionalCache中的数据放到二级缓存中，并且会清空当前SqlSession一级缓存中的数据。
   * <p>
   * 注意： 自己测试的时候必须SqlSession关闭的时候，数据才会存到二级缓存中，所以要是已经配置好，就要关闭SqlSession再次获取去查询。
   */
  @Test
  public  void seeMybatisSourceCode2() {
    try {
      String resource = "com/chenyuan/mybatis-config.xml";
      InputStream inputStream = Resources.getResourceAsStream(resource);
      SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
      System.out.println("-----------------------------");
      SqlSession sqlSession = sqlSessionFactory.openSession();
//            Blog blog = sqlSession.selectOne("com.chenyuan.mapper.BlogMapper.selectBlog", 1);
      BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
      mapper.selectBlog2(2);
      sqlSession.close();

      System.out.println("-----------------------------");
      SqlSession sqlSession2 = sqlSessionFactory.openSession();
//            Blog blog = sqlSession.selectOne("com.chenyuan.mapper.BlogMapper.selectBlog", 1);
      BlogMapper mapper2 = sqlSession2.getMapper(BlogMapper.class);
      mapper2.selectBlog2(2);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
